package com.cskaoyan.config;

import com.cskaoyan.bean.pojo.MarketAdmin;
import com.cskaoyan.bean.pojo.MarketAdminExample;
import com.cskaoyan.bean.pojo.MarketUser;
import com.cskaoyan.bean.pojo.MarketUserExample;
import com.cskaoyan.mapper.MarketAdminMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 创建日期: 2022/04/10 23:10
 *
 * @author HanWeiqi
 */
public class AdminRealm extends AuthorizingRealm {
    @Autowired
    MarketAdminMapper marketAdminMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();

        MarketAdminExample marketAdminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = marketAdminExample.createCriteria();
        if(username!=null && !"".equals(username)) {
            criteria.andUsernameLike(username);
        }
        // 由于用户名唯一，所以如果输入用户名存在，那么这个list只有一条数据
        List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(marketAdminExample);
        // 没有查询到这个用户名，直接返回null
        if (marketAdmins == null || marketAdmins.size() == 0) {
            return null;
        }
        MarketAdmin marketAdmin = marketAdmins.get(0);

        // 得到查询出的用户的密码
        String password = marketAdmin.getPassword();

        return new SimpleAuthenticationInfo(marketAdmin, password, this.getName());
    }
    //获得授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权方法中可以拿到用户信息
        MarketAdmin primaryPrincipal = (MarketAdmin) principalCollection.getPrimaryPrincipal();
        return null;
    }
}
